package cc.comac.mom.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cc.comac.mom.api.EquipDevTypeService;
import cc.comac.mom.bean.EquipDevBean;
import cc.comac.mom.bean.EquipDevType;
import cc.comac.mom.bean.ImportReultData;
import cc.comac.mom.bean.ResultDev;
import cc.comac.mom.datahandlers.entity.EquipDevTypeDataHandler;
import cc.comac.mom.entity.EquipDevCategoryEntity;
import cc.comac.mom.entity.EquipDevEntity;
import cc.comac.mom.entity.EquipDevTypeEntity;
import cc.comac.mom.util.BaseEntityDataUtil;
import cc.comac.mom.util.ExcelUploadUtil;
import cc.comac.mom.util.ResultBean;
import cc.comac.mom.util.TimeUtil;

@Service
@RestController
public class EquipDevTypeServiceImpl implements EquipDevTypeService {

	@Autowired
	private EquipDevTypeDataHandler equipDevTypeDataHandler;

	@Autowired
	private BaseEntityDataUtil baseEntityDataUtil;

	@Override
	public ResultBean insert(@RequestBody EquipDevType equipDevType) {
		ResultBean resultBean = new ResultBean(true);
		int insert = equipDevTypeDataHandler.insert(equipDevType);
		resultBean.setObject(insert);
		return resultBean;
	}

	@Override
	public ResultBean update(@RequestBody EquipDevType equipDevType) {
		ResultBean resultBean = new ResultBean(true);
		int update = equipDevTypeDataHandler.update(equipDevType);
		resultBean.setObject(update);
		return resultBean;
	}

	@Override
	public ResultBean batchDelete(@RequestBody List<EquipDevType> equipDevTypeList) {
		ResultBean resultBean = new ResultBean(true);
		int batchDelete = equipDevTypeDataHandler.batchDelete(equipDevTypeList);
		resultBean.setObject(batchDelete);
		return resultBean;
	}

	@Override
	public ResultDev selectAllByPage(@RequestBody EquipDevType equipDevType) {
		ResultDev selectAllByPage = equipDevTypeDataHandler.selectAllByPage(equipDevType);
		return selectAllByPage;
	}

	@Override
	public ResultDev selectBySomeField(@RequestBody EquipDevType equipDevType) {
		ResultDev selectBySomeField = null;
		if (equipDevType.getSearchAll() != 1) {
			selectBySomeField = equipDevTypeDataHandler.selectBySomeField(equipDevType);
		} else {
			selectBySomeField = equipDevTypeDataHandler.selectBySomeField(equipDevType);
		}
		return selectBySomeField;
	}

	@Override
	public List<EquipDevTypeEntity> getAllEnable() {
		List<EquipDevTypeEntity> allEnable = equipDevTypeDataHandler.getAllEnable();
		return allEnable;
	}

	// 导入数据
	@Override
	public ResultBean importEquipDevType(MultipartFile file, String rootPath) throws IOException {
		ResultBean resultBean = new ResultBean(true);
//		if (file == null || file.isEmpty()) {
//			resultBean.setSuccess(false);
//			resultBean.setMessage("上传失败，请重新上传！");
//			return resultBean;
//		} else if (file.getSize() > 10000000) {
//			resultBean.setSuccess(false);
//			resultBean.setMessage("上传失败，文件大小不能超过10M!！");
//			return resultBean;
//		}
//		String fileName = file.getOriginalFilename();
//		File dir = new File(rootPath);
//		if (!dir.exists()) {
//			dir.mkdir();
//		}
//		File chunkFile = new File(dir, fileName);
//		try {
//			chunkFile.createNewFile();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		file.transferTo(chunkFile);

		// 已存在设备编号
		ArrayList<String> listDevTypeNumber = new ArrayList<String>();
		// 新增的数据集合
		ArrayList<EquipDevTypeEntity> listEntity = new ArrayList<EquipDevTypeEntity>();
		ArrayList<Object> errorList = new ArrayList<Object>();
		// 查询数据库存在的设备编号，添加到已存在的数据集合里
		QueryWrapper<EquipDevTypeEntity> queryWrapper = new QueryWrapper<EquipDevTypeEntity>();
		queryWrapper.eq("row_status", 1);
		List<EquipDevTypeEntity> listEquipDevTypeEntity = equipDevTypeDataHandler.list(queryWrapper);
		if (listEquipDevTypeEntity != null && listEquipDevTypeEntity.size() > 0) {
			for (EquipDevTypeEntity item : listEquipDevTypeEntity) {
				listDevTypeNumber.add(item.getDevTypeNumber());
			}
		}
		try {
			// FileInputStream in = new FileInputStream(file);
//			FileInputStream in = new FileInputStream(chunkFile);
			Workbook workbook;
			workbook = ExcelUploadUtil.getWorkBook(file);
			// Sheet的数量
			int sheetCount = workbook.getNumberOfSheets();
			// 循环sheet
			for (int i = 0; i < sheetCount; i++) {
				Sheet sheetAt = workbook.getSheetAt(i);
				// 行数
				int rowCount = sheetAt.getLastRowNum();
				System.out.println(rowCount + "行数");
				// 跳过第一行
				if (rowCount < 1) {
					continue;
				}
				// 循环行
				for (int j = 1; j <= rowCount; j++) {

					Row row = sheetAt.getRow(j);

					int cellCount = row.getPhysicalNumberOfCells();
					System.out.println(cellCount + "列数");
					Cell cell0 = row.getCell(0);
					Object devTypeNumber = ExcelUploadUtil.getValue(cell0);
					EquipDevTypeEntity equipDevTypeEntity = new EquipDevTypeEntity();
					if (listEquipDevTypeEntity.size() > 0) {
						for (EquipDevTypeEntity equipDevType : listEquipDevTypeEntity) {
							if (StringUtils.isEmpty(devTypeNumber.toString())
									|| equipDevType.getDevTypeNumber().equals(devTypeNumber)) {
								ArrayList<Object> arrayList = new ArrayList<Object>();
								for (Cell cell : row) {
									arrayList.add(ExcelUploadUtil.getValue(cell));
								}
								errorList.add("设备类型编号"+devTypeNumber+"重复");
								errorList.add(arrayList);
							}
						}
					}
					// 数据为空
					if (devTypeNumber == null) {
						continue;
					}
					equipDevTypeEntity.setDevTypeNumber(devTypeNumber.toString());
					// 数据已存在
					if (listDevTypeNumber.contains(devTypeNumber)) {
						// 设备编号已经存在
						continue;
					}
					Object devTypeName = ExcelUploadUtil.getValue(row.getCell(1));
					if (devTypeName != null && devTypeName instanceof String) {
						equipDevTypeEntity.setDevTypeName((String) devTypeName);
					}
					Object remark = ExcelUploadUtil.getValue(row.getCell(2));
					if (remark != null && remark instanceof String) {
						equipDevTypeEntity.setRemark((String) remark);
					}
					Object enable = ExcelUploadUtil.getValue(row.getCell(3));
					if (enable != null && enable instanceof Long) {
						equipDevTypeEntity.setEnable((Long) enable);
					}
					listEntity.add(equipDevTypeEntity);
					listDevTypeNumber.add(devTypeNumber.toString());
				}
			}
//			chunkFile.delete();
			for (EquipDevTypeEntity typeEntity : listEntity) {
				baseEntityDataUtil.setBaseEntityData(typeEntity);
			}
			equipDevTypeDataHandler.saveBatch(listEntity, listEntity.size());
			ImportReultData importReultData = new ImportReultData();
			importReultData.setErrorList(errorList);
			importReultData.setErrorRow(errorList.size());
			importReultData.setSuccessRow(listEntity.size());
			importReultData.setTotalRow(errorList.size() + listEntity.size());
			resultBean.setObject(importReultData);
		} catch (Exception e) {
			e.printStackTrace();
		}
//		chunkFile.delete();
		return resultBean;
	}

	@Override
	public String exportData(HttpServletRequest request, HttpServletResponse response, EquipDevBean obj) {

		return null;
	}
}
